package cd.cdyb.sms.controller.base;

import cd.cdyb.sms.utils.StringUtilPlus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Junpeng.Su
 * @create 2017-07-13 上午 11:49
 * @description 后台异常处理器
 */
@ControllerAdvice
@Controller
public class BackendExceptionController extends ExceptionController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BackendExceptionController.class);

    private static final MappingJackson2JsonView DEFAULT_JSON_VIEW = new MappingJackson2JsonView();

    @Override
    protected ModelAndView prepareExceptionInfo(HttpServletRequest request, HttpServletResponse response, HttpStatus httpStatus, String errorCode, String errorMessage, Exception exception) {
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            LOGGER.error("request param : [{}]=[{}]", entry.getKey(), StringUtilPlus.join(entry.getValue()));
        }

        Map<String, Object> modelsResult = new LinkedHashMap<>();
        modelsResult.put("code", -1);
        modelsResult.put("msg", errorMessage);
        modelsResult.put("data", "");

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setView(DEFAULT_JSON_VIEW);
        modelAndView.addAllObjects(modelsResult);
        return modelAndView;
    }

}
